import dns.resolver
import threading
import socket
import time
import struct
from scapy.all import DNS, DNSQR, IP, Raw

def dns_answer() :
    dns_query = DNS(qd=DNSQR(qname="bilibili", qtype=1))
    # 封装成IP层
    ip_packet = IP(dst='8.8.8.8')
    # 封装成Raw层
    raw_packet = Raw(str(dns_query))
    # 构造最终的DNS网络包
    dns_packet = ip_packet / raw_packet
    
    return dns_packet

def dns_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_address = ('192.168.0.6', 53)
    server_socket.bind(server_address)
    
    print("等待接收数据...")
    while True:
        data, address = server_socket.recvfrom(1024)
        print(f"接收到的数据来自 {address}: {data}")
        server_socket.sendto(data, address)

if __name__=="__main__":
    # 设置DNS服务器，如果不设置，将使用系统默认的DNS服务器
    t = threading.Thread(target=dns_server)
    t.start()
    # time.sleep(1)
    dns_server = '127.0.0.1'
    
    # # 设置域名
    # domain = 'bilibili.com'
    
    # # 设置查询类型，例如A记录、MX记录等
    # query_type = 'A'
    
    # # 创建DNS解析器，并指定DNS服务器
    # resolver = dns.resolver.Resolver()
    # resolver.nameservers = [dns_server]
    
    # # 发起DNS查询
    # answers = resolver.query(domain, query_type)
    
    # # 打印查询结果
    # for rdata in answers:
    #     print(rdata)

    t.join()